<?

/*------------------------------
通用函数
------------------------------*/

/*调试输出*/
function dump($vars, $label = '', $return = false)
{
	if (ini_get('html_errors')) {
		$content = "<pre>\n";
		if ($label != '') {
			$content .= "<strong>{$label} :</strong>\n";
		}
		$content .= htmlspecialchars(print_r($vars, true));
		$content .= "\n</pre>\n";
	} else {
	$content = $label . " :\n" . print_r($vars, true);
	}
	if ($return) { return $content; }
	echo $content;
	return null;
}

/*页面跳转*/
function redirect($url, $delay = 0, $js = false, $jsWrapped = true, $return = false)
{
    $delay = (int)$delay;
    if(!$js){
        if(headers_sent() || $delay > 0){
            echo <<<EOT
<!--    <html>
    <head>-->
    <meta http-equiv="refresh" content="{$delay};URL={$url}" />
<!--    </head>
    </html>-->
EOT;
          //  exit;
        }else{
            header("Location: {$url}");
           // exit;
        }
    }
    $out = '';
    if($jsWrapped){
        $out .= '<script language="JavaScript" type="text/javascript">';
    }
    if($delay > 0){
        $out .= "window.setTimeout(function () { document.location='{$url}'; }, {$delay});";
    }else{
        $out .= "document.location='{$url}';";
    }
    if($jsWrapped){
        $out .= '</script>';
    }
    if($return) {
        return $out;
    }
    //echo $out;
   // exit;
}

//弹出JS消息
function alert($msg){
	echo <<<EOT
<!--	<html>
	<body>-->
	<script language="JavaScript" type="text/javascript">
	<!--
		alert("$msg");
	-->
	</script>
<!--	</body>
	</html>-->
EOT;
}

//后台消息框
function msg($msg,$title=""){
	$msg = "<dd>$msg</dd>";
	if($title) $title="<dt>$title</dt>";
	echo <<<EOT
	<div class="msgbox">
		<dl>
			$title
			$msg
		</dl>
	</div>
EOT;
}


//读文件
function rfile($f){
	if(file_exists($f)){
		return file_get_contents($f);
	}else{
		return false;
	}	
}

//写入文件
function wfile($f,$c){
	if(makeDir(dirname($f))){
		if($fp = fopen($f,"w")){
			@flock($fp,LOCK_EX);
			if(@fwrite($fp,$c)){
				@flock($fp,LOCK_UN);
				fclose($fp);
				return true;
			}else {
				@flock($fp,LOCK_UN);
				fclose($fp);
				return false;
			}
		}
	}	
}

//创建目录
function makeDir( $dir, $mode = "0777" ){
	if( ! $dir ) return 0;
	$dir = str_replace( "\\", "/", $dir );
	$mdir = "";
	foreach( explode( "/", $dir ) as $val ) {
		$mdir .= $val."/";
		if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
		if( ! file_exists( $mdir ) ) {
			if(!@mkdir( $mdir, $mode )){
				return false;
			}
		}
	}
	return true;
}

?>